import {Injectable} from '@angular/core';
import {AppConfig} from '../config';
import {HttpClient} from '@angular/common/http';

@Injectable()
export class UploadService {

  private readonly param = 'faults';

  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  constructor(private http: HttpClient) {
  }

  // upFile(file,schemeId,multipleValue) {
  //   let options = new RequestOptions({
  //     headers: new Headers({ 'Content-Type': 'multipart/form-data' }),
  //   });
  //   let formData = new FormData();
  //   formData.append("file", file[0], file[0].name);
  //   formData.append("schemeId", schemeId);
  //   const url = `${this.url}/uploadExcel/schemeId/${schemeId}/multipleValue/${multipleValue}`;
  //   return this.http.post(url, formData,options)
  //     .toPromise()
  //     .then(res => {
  //       try {
  //         let result = res;
  //         switch (result.code) {
  //           case "1":
  //             return result.data;
  //           case "0":
  //             throw new Error(result.message);
  //         }
  //       }
  //       catch (error) {
  //         this.handleError(error);
  //       }
  //     })
  //     .catch(this.handleError);
  // }

  upFile(file, schemeId, multipleValue) {

    let formData = new FormData();
    formData.append('file', file[0], file[0].name);
    const url = `${this.url}/uploadExcel/schemeId/${schemeId}/multipleValue/${multipleValue}`;
    return this.http.post(url, formData)
      .toPromise()
      .then(res => {
        try {
          let result = res as any;
          switch (result.code) {
            case '200':
              return result.data;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          this.handleError(error);
        }
      })
      .catch(this.handleError);
  }


  // upFile(schemeId: number):any {
  //   const url = `${this.url}/getBasicFaultById/${schemeId}`;
  //   return this.http.get(url)
  //   .toPromise()
  //   .then(response => response.data )
  //   .catch(this.handleError)
  // }


  private handleError(error: any): Promise<any> {
    return Promise.reject(error.message || error);
  }


}


// WEBPACK FOOTER //
// ./src/app/service/upload.service.ts
